﻿using System;
using System.Collections.Generic;
using System.Data;
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http; 
using U8Login;
using UFIDA.U8.MomServiceCommon;
using FERROU8API.Pub;

namespace FERROU8API.Plugin
{
    public class ArrsourcePlugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Arrsourceapi";
        public static string constr = "";
        private string url = "";

        /// <summary>
        /// 采购订单
        /// </summary>
        /// <param name="login"></param>
        /// <param name="domhead"></param>
        /// <param name="dombody"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        private String GetCustJs(clsLogin login, MSXML2.IXMLDOMDocument2 domhead, MSXML2.IXMLDOMDocument2 dombody, int operation)
        {
            var datatable = Common.GetUrl(constr, login.get_cAcc_Id()).Tables[0];
            var datarow = datatable.Rows[0];
            url = datarow[1] + "Arrsourceapi";
            //var datatabledept = Common.GetUser(constr).Tables[0];
            //DebugWriteLog.WriteLine("cAcc_Id:" + login.get_cAcc_Id() + ",count:" + datatabledept.Rows.Count);
            //bool hasdept = false;
            //foreach (DataRow item in datatabledept.Rows)
            //{
            //    //部门code
            //    var deptcode = item[1].ToString();
            //    //过滤如果不是QZ不触发插件
            //    if (deptcode == login.get_cAcc_Id())
            //    {
            //        DebugWriteLog.WriteLine("cAcc_Id:" + login.get_cAcc_Id() + ",deptcode:" + deptcode);
            //        hasdept = true;
            //    }
            //}
            //if (!hasdept)//限制
            //{
            //    return "Nopermission";
            //}
            #region 注释
            //MSXML2.IXMLDOMNode tmpNode = domhead.selectSingleNode("/customer");
            //String custcode = tmpNode.attributes.getNamedItem("ccuscode").nodeValue.ObjToString();
            //String custname = tmpNode.attributes.getNamedItem("ccusname").nodeValue.ObjToString();
            //string ccode = tmpNode.attributes.getNamedItem("ccccode").nodeValue.ObjToString(); 
            #endregion

            MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");

            string pocode = tmphead.attributes.getNamedItem("cpoid").nodeValue.ObjToString();//采购订单号
            int cbustype = tmphead.attributes.getNamedItem("cbustype").nodeValue.ObjToInt32();//业务类型
            string vencode = tmphead.attributes.getNamedItem("cvencode").nodeValue.ObjToString();//供应商编号
            string depcode = tmphead.attributes.getNamedItem("cdepcode").nodeValue.ObjToString();//部门编码
            string usercode = tmphead.attributes.getNamedItem("cpersoncode").nodeValue.ObjToString();//人员编码
            int poid = tmphead.attributes.getNamedItem("poid").nodeValue.ObjToInt32();//采购订单主表ID
            DateTime podate = tmphead.attributes.getNamedItem("dpodate").nodeValue.ObjToDate();//单据时间
            string bz = tmphead.attributes.getNamedItem("cexch_name").nodeValue.ObjToString();//币种 cexch_name 
            float exchangeRate = tmphead.attributes.getNamedItem("nflat").nodeValue.ObjToFloat();//汇率
            float taxRate = tmphead.attributes.getNamedItem("itaxrate").nodeValue.ObjToFloat();//税率 iTaxRate
          
            string sql = @"select ivouchrowno,id,iquantity,cinvcode,
                         iunitprice,itaxprice,imoney,isum,itax,inatunitprice,
                         inatmoney,inatsum,inattax,cFree1,cFree2,cFree3
                         from PO_Podetails with(nolock) where poid = " + poid;

            DebugWriteLog.WriteLine(sql+"---"+constr);
            DataTable table = DbHelperSQL.Query(sql, constr, null).Tables[0];
            DebugWriteLog.WriteLine(table.Rows.Count + "---");
            //var table = DbHelperSQL.Query(sql, constr, null).Tables[0];

            List<Arrsourceapi> dlist = new List<Arrsourceapi>();

            try
            {
                foreach (DataRow item in table.Rows)
                {
                    decimal qty = item["iquantity"].ObjToDecimal();//数量
                    string cinvCode = item["cinvcode"].ObjToString();//存货编码
                    int poSeq = item["ivouchrowno"].ObjToInt32();//行号
                    int podid = item["id"].ObjToInt32();//销售订单号
                    Int32 StartFlag = 0;
                    Arrsourceapi m = new Arrsourceapi();
                    m.PoCode = pocode;
                    m.PoID = poid;
                    m.PoDid = podid;
                    m.PoSeq = poSeq;
                    m.CinvCode = cinvCode;
                    m.Qty = qty;
                    m.CBusType = cbustype;
                    m.VendorCode = vencode;
                    m.DeptCode = depcode;
                    m.UserCode = usercode;
                    m.PoDate = podate;
                    m.Bz = bz;
                    m.ExchangeRate = exchangeRate;
                    m.TaxRate = taxRate;
                    m.OriPrice = item["iunitprice"].ObjToDecimal();
                    m.OriTaxPrice = item["itaxprice"].ObjToDecimal();
                    m.IOriSum = item["imoney"].ObjToDecimal();//iMoney
                    m.IOriTaxSum = item["isum"].ObjToDecimal();
                    m.IOriTax = item["itax"].ObjToDecimal();
                    m.Status = StartFlag;
                    m.LocalPrice = item["inatunitprice"].ObjToDecimal();
                    //m.LocalTaxPrice = item["inatunitprice"].ObjToString();
                    m.ILocalSum = item["inatmoney"].ObjToDecimal();
                    m.ILocalTaxSum = item["inatsum"].ObjToDecimal();
                    m.IlocalTax = item["inattax"].ObjToDecimal();
                    m.Free1 = item["cFree1"].ToString(); // 国内/国外关联非关联(te)
                    m.Free2 = item["cFree2"].ToString(); //供应商(te)
                    m.Free3 = item["cFree3"].ToString(); //空值

                    dlist.Add(m);
                }
            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("采购单接口异常抛出", "GetCustJs", e.ToJson());
                throw e;
            }

            ApiRequest req = new ApiRequest();
            req.data = dlist;
            req.orgcode = login.get_cAcc_Id();
            req.primarykey = pocode;
            req.operation = operation;
            DebugWriteLog.WriteLine("采购单接口", "GetCustJs", req.ToJson());
            return req.ToJson();
        }
        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 2);

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("采购单接口", "Update_After", ex.ToJson());
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
        public bool Insert_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 0);

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("采购单接口", "Insert_After", ex.ToJson());
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
        public bool Delete_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 1);

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("采购单接口", "Delete_After", ex.ToJson());
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
    }
}